package com.example.controller;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;

/**
 * &#064;purpose  rest风格控制器
 * &#064;note  用于演示普通接口的使用
 * &#064;author yanglong
 * &#064;time  2025年3月7日10:07:20
 */
@RestController
public class DemoController {


    /**
     * 测试普通参数的接口
     */
    @RequestMapping(path = "/some")
    public String some(@RequestParam String username, @RequestParam String school,@RequestParam int age) {
        /* 简单组装字符串 */
        String content = "Hello " + username + ",you are graduate from " + school + ",and your age is " + age;
        return  content;
    }

    /**
     * 测试接受http请求的body参数
     */
    @PostMapping(path = "/any")
    public String any(@RequestBody Map<String, Object> requestBody) {
        /* java 语法，方法的参数使用注解 参数类型使用key和value */
        String username = (String) requestBody.getOrDefault("username", "Guest");
        /* 获取body的参数 和php一样可以使用括号+类型强转变量类型 */
        String school = (String) requestBody.getOrDefault("school", "Unknown School");
        int age = (int) requestBody.getOrDefault("age", 0);
        /* for循环 */
        for(int i =0; i<10; i++){
            /* 系统打印长字符串，就是控制台打印 */
            System.out.println(username + " " + school + " " + age + " " + i);
        }

        // 遍历并打印 requestBody 中的键值对
        /* Map.Entry<String, Object> 是变量类型 entry是变量名称  */
        /* requestBody.entrySet()是将body调用entrySet设置参数变量 */
        for (Map.Entry<String, Object> entry : requestBody.entrySet()) {
            /* 获取参数名称 */
            String key = entry.getKey();
            /* 获取参数的值 */
            Object value = entry.getValue();
            /* 系统打印长字符串 */
            System.out.println("Key: " + key + ", Value: " + value);
        }

        /* 拼接字符串 */
        String content = "Hello " + username + ", you are graduate from " + school + ", and your age is " + age;
        return content;
    }
}
